<template>
  <div class="app-container">
    <h1 style="margin-top:10px">这里是共享屏幕示例</h1>
    <video id="video" autoplay controls ref="myVideo"></video>
    <div class="btn-group">
      <el-button size="small" type="primary" @click="takeSnap">截屏</el-button>
    </div>
  </div>
</template>
<script>
import { defineComponent, onMounted, reactive, toRefs,ref  } from "vue";

export default defineComponent({
  setup() {
    let myVideo=ref(null)
    let state = reactive({
      stream: {},
      videoTracks: [],
    });
    onMounted(() => {
      openScreenShare();
    });
    const openScreenShare =async () => {
      try {
        state.stream = await navigator.mediaDevices.getDisplayMedia({
          video: true,
        });
        console.log("success");
        handleSuccess();
      } catch (e) {
        console.log(e);
      }
    };
    const handleSuccess = () => {
      let tmpV=document.getElementById('video')
      tmpV.srcObject = state.stream;
    };
    const takeSnap=()=>{
      const canvas=document.createElement('canvas')
      const a=document.createElement('a')
      const ctx=canvas.getContext('2d')
      const video=document.querySelector('#video')
      canvas.width=1000;
      canvas.height=1000;
      ctx.drawImage(video,0,0)
      let url=canvas.toDataURL('image/jpg')
      a.download=new Date().toLocaleString()
      a.href=url
      a.click()
      document.body.removeChild(a);
    }
    return {
      ...toRefs(state),
      myVideo,
      takeSnap
    };
  },
});
</script>
<style scoped>
.app-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
#video {
  box-sizing: border-box;
  padding: 0 10px;
  width: 100%;
  height: 500px;
}
.btn-group {
  display: flex;
  flex-direction: row;
  margin-top: 10px;
}
</style>
